import { createRouter, createWebHistory } from 'vue-router';
import Login from '../views/auth/Login.vue';
import StudentList from '../views/student/index.vue';
import StudentGrades from '../components/StudentGrades.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/students',
    name: 'StudentList',
    component: StudentList,
    meta: { requiresAuth: true, roles: ['teacher'] }
  },
  {
    path: '/student/:id',
    name: 'StudentDetail',
    component: StudentGrades,
    meta: { requiresAuth: true }
  },
  {
    path: '/',
    redirect: '/login'
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token');
  const user = JSON.parse(localStorage.getItem('user') || '{}');

  // 需要认证的页面
  if (to.meta.requiresAuth) {
    if (!token) {
      next('/login');
      return;
    }

    // 角色权限检查
    if (to.meta.roles && !to.meta.roles.includes(user.role)) {
      next('/login');
      return;
    }

    // 学生用户只能访问自己的详情页
    if (user.role === 'user' && to.name === 'StudentDetail') {
      if (to.params.id !== user.studentId) {
        next('/login');
        return;
      }
    }
  }

  // 已登录用户访问登录页，重定向到首页
  if (to.path === '/login' && token) {
    if (user.role === 'teacher') {
      next('/students');
    } else {
      next(`/student/${user.studentId}`);
    }
    return;
  }

  next();
});

export default router;